import { Component, ReactNode, memo } from "react";
import { Textarea, View, Text, Image, Picker, Input } from "@tarojs/components";
import "./index.scss";
import {
  AtList,
  AtListItem,
  AtImagePicker,
  AtButton,
  message,
  AtNavBar,
} from "taro-ui";
import i1 from "./images/i1.png";
import i2 from "./images/i2.png";
import { isEmpty, uploadImgConvertUrl } from "../../utils/kit";
import Taro from "@tarojs/taro";
import Req, { BASE_URL } from "../../utils/request";
import ProjectSelect from "../../components/ProjectSelect";
export default class OperationForm extends Component {
  state = {
    files: [],
    memo: "",
    location: "",
    x: "", //经度
    y: "", //纬度
    progressDate: "",
    projectName: "",
    projectId: "",
    projectIsOpen: false,
    revenue: "",
    profit: "",
  };
  get navBarTitle() {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      return "运营编辑";
    }
    return "运营新增";
  }
  componentDidMount(): void {
    this.initData();
  }
  onDateChange = (e) => {
    console.log(e);
    this.setState({
      progressDate: e.detail.value,
    });
  };
  onChange = (files) => {
    console.log(files);
    this.setState({
      files,
    });
  };
  initData = () => {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      Taro.setNavigationBarTitle({
        title: "运营编辑",
      });
      Req.get("/project/progress/" + router.params.id).then((r) => {
        if (r.code === 200) {
          let _files = [];
          if (r.data.img) {
            _files = r.data.img.split(",").map((e) => {
              return {
                url: BASE_URL + e,
              };
            });
          }
          this.setState({
            projectName: r.data.projectName,
            memo: r.data.memo,
            location: r.data.location,
            progressDate: r.data.deadline,
            x: r.data.x,
            y: r.data.y,
            img: r.data.img,
            profit: r.data.profit,
            revenue: r.data.revenue,
            files: _files,
          });
        }
      });
    }
  };
  onOpenLocation = () => {
    Taro.chooseLocation({
      success: (res) => {
        console.log("位置名称：", res.name);
        console.log("经纬度：", res.latitude, res.longitude);
        this.setState({
          location: res.name,
          x: res.latitude,
          y: res.longitude,
        });
      },
      fail: (err) => {
        console.error("错误信息：", err.errMsg);
      },
      complete: () => {
        console.log("选择操作完成");
      },
    });
  };
  onChangeProjects = () => {
    this.setState({
      projectIsOpen: true,
    });
  };
  onSubmit = () => {
    const { router } = Taro.getCurrentInstance();
    const {
      location,
      x,
      y,
      memo,
      progressDate,
      projectId,
      files,
      revenue,
      profit,
      projectName
    } = this.state;

    if(isEmpty(projectName)){
      Taro.showToast({
        title: "项目不能为空！",
        icon: "none",
        duration: 2000,
      })
      return
    }
    if(isEmpty(revenue)){
      Taro.showToast({
        title: "项目营收不能为空！",
        icon: "none",
        duration: 2000,
      })
      return
    }
    if(isEmpty(profit)){
      Taro.showToast({
        title: "项目利润不能为空！",
        icon: "none",
        duration: 2000,
      })
      return
    }
    if(isEmpty(progressDate)){
      Taro.showToast({
        title: "截止日期不能为空！",
        icon: "none",
        duration: 2000,
      })
      return 
    }


    uploadImgConvertUrl(files).then((results) => {
      let img = results
        .map((e: any) => {
          if (e?.data) {
            return JSON.parse(e.data)?.fileName;
          } else {
            return e.fileName;
          }
        })
        .join(",");
      if (router?.params.id) {
        Req.post("/project/progress/edit", {
          id: router.params.id,
          projectId: projectId, //需要选择项目
          location,
          x,
          y,
          memo,
          revenue,
          profit,
          deadline: progressDate,
          img,
        })
          .then((r) => {
            if (r.code === 200) {
              Taro.showToast({
                title: "操作成功！",
                icon: "none",
                duration: 2000,
              });
              setTimeout(() => {
                //通知上一个页面刷新数据
                Taro.eventCenter.trigger("refreshData", { force: true });
                Taro.navigateBack();
              }, 2000);
            }
          })
          .catch((e) => {});
      } else {
        Req.post("/project/progress/add", {
          projectId: projectId, //需要选择项目
          location,
          x,
          y,
          memo,
          revenue,
          profit,
          deadline: progressDate,
          img,
        })
          .then((r) => {
            if (r.code === 200) {
              Taro.showToast({
                title: "操作成功！",
                icon: "none",
                duration: 2000,
              });
              setTimeout(() => {
                //通知上一个页面刷新数据
                Taro.eventCenter.trigger("refreshData", { force: true });
                Taro.navigateBack();
              }, 200);
            }
          })
          .catch((e) => {});
      }
    });
  };
  render(): ReactNode {
    const { memo, progressDate, location, projectName, revenue, profit } =
      this.state;
    return (
      <View className="of-container app-container list-form-page">
        <AtNavBar
          leftIconType="chevron-left"
          leftText="返回"
          color="#3051BE"
          onClickLeftIcon={() => {
            Taro.navigateBack();
          }}
        >
          {this.navBarTitle}
        </AtNavBar>
        <AtList className="list-form-content">
          <AtListItem
            onClick={this.onChangeProjects}
            title="项目"
            className="form-list-item form-label-required"
            note={
              <View>
                <Text>{isEmpty(projectName) ? "请选择" : projectName}</Text>
              </View>
            }
            arrow="down"
          />
          <AtListItem
            title="内容"
            className="form-list-item no-active-effect-item remark-form-item no-arrow-space"
            note={
              <View>
                <Textarea
                  value={memo}
                  onInput={(e) => {
                    this.setState({
                      memo: e.detail.value,
                    });
                  }}
                  className="remark-textarea"
                  placeholder="请输入文字"
                />
              </View>
            }
            extraText={
              <View className="img-picker">
                <AtImagePicker
                  length={1}
                  files={this.state.files}
                  onChange={this.onChange}
                />
              </View>
            }
          />
          {/* <AtListItem
            onClick={this.onOpenLocation}
            title="定位"
            className="form-list-item no-arrow-space"
            note={
              <View className="select-content">
                <Text>{isEmpty(location) ? "请选择定位" : location}</Text>
                <Image className="right-icon" src={i1} />
              </View>
            }
          /> */}

          <AtListItem
            title="项目营收"
            className="form-list-item no-active-effect-item form-label-required"
            extraText={"万元"}
            note={
              <View>
                <Input
                  value={revenue}
                  placeholder="请输入"
                  type="digit"
                  onInput={(e) => {
                    this.setState({
                      revenue: e.detail.value,
                    });
                  }}
                />
              </View>
            }
          />
          <AtListItem
            title="项目利润"
            className="form-list-item no-active-effect-item form-label-required"
            extraText={"万元"}
            note={
              <View>
                <Input
                  type="digit"
                  value={profit}
                  placeholder="请输入"
                  onInput={(e) => {
                    this.setState({
                      profit: e.detail.value,
                    });
                  }}
                />
              </View>
            }
          />
          <Picker value={progressDate} mode="date" onChange={this.onDateChange}>
            <AtListItem
              title="截止日期"
              className="form-list-item no-arrow-space form-label-required"
              note={
                <View className="select-content">
                  <Text>
                    {isEmpty(progressDate) ? "请选择日期" : progressDate}
                  </Text>
                  <Image className="right-icon" src={i2} />
                </View>
              }
            />
          </Picker>
        </AtList>
        <AtButton
          onClick={this.onSubmit}
          circle
          className="primary-btn-color list-bottom-btn"
          type="primary"
        >
          提交
        </AtButton>

        <ProjectSelect
          visible={this.state.projectIsOpen}
          onClose={() => {
            this.setState({
              projectIsOpen: false,
            });
          }}
          onSelect={(row: any) => {
            this.setState({
              projectIsOpen: false,
              projectName: row.title,
              projectId: row.id,
            });
          }}
        />
      </View>
    );
  }
}
